const router = require("koa-router")();
const CarModel = require("../models/car.js");
const AccountModel = require("../models/account.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");
const formatDateHelper = require('../utils/formatDateHelper.js')


router.get("/cars", async ctx => {
	let {
		page,
		limit,
		number,
		user_id,
		id
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};
	
	
	// 构建查询条件
	if (number) {
		query.number = {
			$regex: ctx.query.number
		}; // 不区分大小写的正则表达式
	}
	
	if (user_id != undefined &&  user_id !== '0') {
		query.user_id = user_id;
	}
	
	if (id != undefined &&  id !== '0') {
		query.id = id;
	}
	

	var data = await CarModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await CarModel.find(query).countDocuments();

	const enhancedData = await Promise.all(data.map(async car => {
		const user = await AccountModel.findOne({
			id: car.user_id
		});
		
		return {
			...car.toObject(), 
			user
		};
	}));
	ctx.body = {
		code: 200,
		data: enhancedData,
		total,
		msg: "ok"
	}

})

router.post("/car", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		number,
		car_number,
		user_id,
		create,
		modify
	} = ctx.request.body;
	
	if (!number) {
		return ResultHelper.errInfo422(ctx, "请填写编号")
	}
	
	if (!id) {
		const numberTrue = await CarModel.findOne({
			number: ctx.request.body.number
		});
		if(numberTrue) {
			return ResultHelper.errInfo422(ctx, "请填写编号")
		}
		const carPost = new CarModel({
			id,
			number,
			car_number,
			user_id,
			create,
			modify
		});
		const res = await carPost.save();
		ctx.body = {
			code: 200,
			msg: "添加成功"
		}
	} else {
		// 已存在数据
		// 获取下数据的内容
		const item = await CarModel.findOne({
			id: ctx.request.body.id
		});
		const res = await CarModel.updateOne({
			id: id
		}, {
			$set: {
				id,
				number: ctx.request.body.number ? ctx.request.body.number : item.number,
				car_number: ctx.request.body.car_number ? ctx.request.body.car_number : item.car_number,
				user_id: ctx.request.body.user_id ? ctx.request.body.user_id : item.user_id,
				create: ctx.request.body.create ? ctx.request.body.create : item.create,
				modify: formatDateHelper.date()
			}
		});
		ctx.body = {
			code: 200,
			msg: "编辑成功"
		}
	}
})

router.get("/del/car", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id
	} = ctx.request.query;
	let res = await CarModel.deleteOne({
		id: id
	});
	ctx.body = {
		code: 200,
		msg: '删除成功'
	}
})


module.exports = router;
